package com.you.common.aspect;

import com.you.common.exception.UserException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *<p>
 *切面处理
 *</p>
 *
 * @author : liu.yang.
 * @date : 2018-07-08 星期日 18:30:57
 * @since : 1.0.0
 */
@Aspect
@Component
public class CommonAspect {
    private final static Logger LOG = LoggerFactory.getLogger(CommonAspect.class);

    @Pointcut("execution(* com.you.modules..*.*(..))")
    public void pcException() {
    }


    @AfterThrowing(pointcut = "pcException()", throwing = "e")
    public void doException(JoinPoint joinPoint, UserException e) {
        if (null != e) {
            Logger log = LoggerFactory.getLogger(joinPoint.getSignature().getClass());
            log.error(e.getMessage(), e);
        }
    }

    @Pointcut("execution(* com.you.modules..*controller.*(..))")
    public void pcLog() {
    }

    @Before("pcLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        LOG.info("request info: url={},method={},ip={}", request.getRequestURL(), request.getMethod(), request.getRemoteAddr());

        LOG.info("class_method={},args={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), joinPoint.getArgs());
    }

    @AfterReturning(returning = "object", pointcut = "pcLog()")
    public void doAfterReturning(Object object) {
        LOG.info("response={}", object.toString());
    }
}
